import QueueAnim from 'rc-queue-anim';
import React from 'react'
import {inject, observer} from 'mobx-react';
import { Route, withRouter } from 'react-router-dom';
import {Icon,ListView,Tools, List,Modal,Popover} from 'weaver-mobile';
import {toJS} from 'mobx';
import OpenAttach from '../fileView/openattach';
import {attachAlert,downloadFile} from '../../util/Utils'
const getLabel = Tools.getLabel;

@withRouter
@inject('docStore')
@observer
export default class AttachRoute extends React.Component {
  openAttach(attach,docInfo){
    const {docStore, path,location} = this.props;
    docStore.attachRowdata = attach;
    const {search} = location
    const isiPhone = Tools.mobileDetect().is('iPhone');
    let urlParams = search.slice(search.indexOf('?') + 1);
    let id = docStore.id
    let ddcode = attach.ddcode || "";
    let randomParams = Math.ceil(Math.random() * 1000);
    let fileurl = `/weaver/weaver.file.FileDownload?fileid=${attach.imagefileid}&download=1&from_doc_mobile=1&randomParams=${randomParams}`;
    //钉钉与em7集成，下载附件丢失session解决方法
    if(ddcode){
      fileurl = fileurl + `&ddcode=${ddcode}`
    }
    //嵌套在iframe中带过来的参数
    if(docStore.otherMouldiframeParams){
      fileurl = fileurl + `&${docStore.otherMouldiframeParams}`
    }
    //在链接中传过来的参数
    if(urlParams){
      fileurl = fileurl + `&${urlParams}`
    }
    if(attach.readOnLine==='1'){
      let attachtype = attach.ficon.iconType;
      if(attachtype === 'pdf' && isiPhone && docInfo.doc_acc_isalert_modal === '0' && docInfo.doc_pdf_download === "1"){
          downloadFile(fileurl,attach.imagefileid);
      }else{
        (docInfo.doc_acc_isalert_modal || '0') === '1'
        ? docInfo.candownload
          ? Modal.alert(getLabel(24960,'提示信息'), getLabel('18214,30662', "请您选择操作方式"), [
              { text: getLabel(258, '下载'),onPress:()=>{
                downloadFile(fileurl,attach.imagefileid);
              }},
              { text: getLabel(221, '预览'), onPress: () => {
                this.props.history.push(`${path || ''}/doc/${id}/attach/list/iframe/${attach.imagefileid}?${docStore.otherMouldiframeParams}`);
                }
              },
            ])
          : this.props.history.push(`${path || ''}/doc/${id}/attach/list/iframe/${attach.imagefileid}?${docStore.otherMouldiframeParams}`)
        : this.props.history.push(`${path || ''}/doc/${id}/attach/list/iframe/${attach.imagefileid}?${docStore.otherMouldiframeParams}`);
      }
    }else{
      attachAlert(attach,docInfo,fileurl);
    }
  }
  //附件打开组件卸载时执行
  attachUnMount = () =>{
    const {docStore} = this.props;
    docStore.attachRowdata = {};
  }
  selectMenuElli = (item,index,rowData) =>{
  	 const {docStore} = this.props,{id} = docStore;
  	 docStore.setAttOperate(rowData.imagefileid,false);
  	 if(item.key == "download"){
  	 	this.toDownload(rowData);
  	 }else if(item.key == "editAcc"){
  	 	this.props.history.push(`/add/39?id=${id}&imagefileid=${rowData.imagefileid}`);
  	 }
  	 
  }
  
  toDownload = (rowData) =>{
  	const {docStore} = this.props,{otherMouldiframeParams} = docStore
  	let randomParams = Math.ceil(Math.random() * 1000);
    // window.open(`/weaver/weaver.file.FileDownload?fileid=${rowData.imagefileid}&download=1`);
    let url = `/weaver/weaver.file.FileDownload?fileid=${rowData.imagefileid}&download=1&from_doc_mobile=1&randomParams=${randomParams}`;
    
    let ddcode = rowData.ddcode;
    if(ddcode){
      url = url + `&ddcode=${ddcode}`;
    }
    if(otherMouldiframeParams){
      url = url + `&${otherMouldiframeParams}`;
    }
    downloadFile(url,rowData.imagefileid);
  }
  
  render() {
    const {docStore, path} = this.props,{attachsListDatasource,attachRowdata,attOperateVisible,attOperateId} = docStore;
    let docInfo = toJS(docStore.docInfo) || {};
    const attachListPath = `${path || ''}/doc/:id/attach/list`;
    return (
      <Route
        key="doc-attach-list"
        path={attachListPath}
        render={() => {
          return (
            <QueueAnim>
              <div className="wm-route-layout"
                   key="doc-attach-list-div">
                    <Route
                      key="news-doc"
                      path={`${path || ''}/doc/:id/attach/list/iframe/:fileid`}
                      render={() => {
                        return (
                          <QueueAnim>
                            <div className="wm-route-layout" key="news-doc-div">
                              <OpenAttach 
                                dataParams={{title:attachRowdata.filename,prevTitle:docInfo.docTitle}}
                                unmount={() => this.attachUnMount()}
                              />
                            </div>
                          </QueueAnim>
                        );
                      }}
                    />
                <div className="wea-doc-attach-list">
                  {
                    Array.isArray(docInfo.docAttrs) && docInfo.docAttrs.length === 0?
                    <div className="wea-doc-whitebg">
                      <div className="wea-doc-error">
                        <Icon type="no-data" size="lg"/>
                        <div>{getLabel(390463, "暂无附件")}</div>
                      </div>
                    </div>:
                    Array.isArray(docInfo.docAttrs) &&
                  <div className="doc-attach-list">
                    <ListView
                      dataSource={attachsListDatasource}
                      renderRow={(rowData, sectionID, rowID) => {
                        return (
                          <List.Item onClick={() => this.openAttach(rowData,docInfo)}>
                            <div key={rowData.imagefileid} className="doc-attach-item">
                              {
                                rowData.ficon ? (
                                  rowData.ficon.iconUrl ?
                                    <img src={rowData.ficon.iconUrl} alt=""/>
                                    :
                                    <Icon type={`${rowData.ficon.iconType}`} size="lg" color={`${rowData.ficon.iconColor}`}/>
                                  ):
                                  <Icon type="rar" size="lg" color="#716BFF"/>
                              }
                              <div className="doc-attach-item-content">
                                <div className="doc-attach-item-title">{rowData.filename}</div>
                                <div className="doc-attach-item-fileSize">
                                  <span>{rowData.fileSizeStr}</span>
                                  <span style={{marginLeft:10}}>{rowData.mainFile}</span>                           
                                </div>
                              </div>
                                <div className="doc-attach-item-download" style={
                                  docInfo.candownload 
                                    ? rowData.readOnLine==='0'
                                      ? (docInfo.doc_acc_isdownload || '1') === '0'
                                        ?{display:'none'}
                                        :{display:'block'}
                                      :{display:'block'}
                                    :{display:'none'}}                  
                                      onClick={(e) =>  {
                                        e.stopPropagation();
                                        if(!(rowData.canEditDoc || rowData.canEditAcc)){
	                                        this.toDownload(rowData);
                                        }
                                      }}
                                  >
                                  {
                                  	rowData.canEditDoc || rowData.canEditAcc ?
                                  	
									 <Popover
							            mask
							            key="docdetail-menu-popover"
							            visible={attOperateVisible && attOperateId == rowData.imagefileid}
							            overlay={[
							                <Popover.Item  key="editAcc">{rowData.canEditDoc ? getLabel(93, '编辑') : getLabel(129740, '编辑附件')}</Popover.Item>,
							                <Popover.Item  key="download">{getLabel(129740, '下载')}</Popover.Item>,
							            ]}
							            onVisibleChange={(visble)=>{
							            	docStore.setAttOperate(rowData.imagefileid,visble);
							            }}
							            onSelect={(item,index)=>{
							            	this.selectMenuElli(item,index,rowData)
							            }}
							          >
							            <span className="doc-title-icon">
							              <Icon type="ellipsis" size="xs"/>
							            </span>
							          </Popover>

                                  	:
                                  	<Icon type="download" size="xs" style={{ marginRight: '4px' }}/>
                                  }
                                </div>
                            </div>
                          </List.Item>
                        );
                      }}
                      className="doc-attach-am-list"
                      style={{height:'100%'}}
                      pageSize={20}
                      initialListSize={20}
                      scrollRenderAheadDistance={500}
                      onEndReachedThreshold={10}
                    />
                  </div>
                  }

                </div>
              </div>
            </QueueAnim>
          );
        }}
      />
    );
  }
}